package cn.mw.cmdb.template.strategy;

import cn.mw.cmdb.exception.ZabbixResultException;
import cn.mw.cmdb.template.enums.TemplateImportExportTypeEnum;
import cn.mw.cmdb.template.param.MwTemplateConfigurationParam;
import cn.mw.main.api.common.ZabbixDubboService;
import cn.mw.microMonitorCommon.constants.ZabbixApiConstants;
import cn.mw.microMonitorCommon.constants.ZabbixMethodConstants;
import cn.mw.microMonitorCommon.entity.zabbix.MWZabbixAPIResult;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description 策略抽象类
 */
@Slf4j
public abstract class TemplateImportExportHandler {

    @DubboReference(check = false, timeout = 120000)
    public ZabbixDubboService zabbixDubboService;

    public final String options = "options";
    public final String templates = "templates";
    public final String FORMAT = "format";
    public final String RULE = "rules";
    public final String SOURCE = "source";


    public abstract TemplateImportExportTypeEnum handlerType();


    //导出模板
    public abstract void exportTemplate(MwTemplateConfigurationParam param, HttpServletResponse response) throws Exception;


    //导入模板
    public abstract void importTemplate(MwTemplateConfigurationParam param, MultipartFile file) throws Exception;


    public String getExportData(MwTemplateConfigurationParam param){
        Map zabbixParam = new HashMap();
        Map templateIdMap = new HashMap();
        templateIdMap.put(templates,param.getTemplateIds());
        zabbixParam.put(options,templateIdMap);
        zabbixParam.put(FORMAT,param.getFileType());
        MWZabbixAPIResult result = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, param.getServerId(), ZabbixMethodConstants.CONFIGURATION_EXPORT, zabbixParam);
        if(result == null || result.isFail()){
            throw new ZabbixResultException(String.valueOf(result.getData()));
        }
        String data = result.getData().toString();
        return data;
    }

    public void exportTemplateData(HttpServletResponse response,String data,String fileName) throws IOException {
        OutputStream out = null;
        try {
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            // 将YAML内容写入响应的输出流中
            out = response.getOutputStream();
            out.write(data.getBytes());
            out.flush();
        }catch (Throwable e){
            log.error("导出模板失败：",e);
        }finally {
            if(out != null){
                out.close();
            }
        }
    }

    public String getImportDataInfo(MultipartFile file) throws Exception {
        // 获取输入流
        InputStream inputStream = file.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        String importData = bufferedReader.lines().collect(Collectors.joining(System.lineSeparator()));
        inputStream.close();
        return importData;
    }

    public void delMapNullValue(Map dataMap){
        Iterator iterator = dataMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            if(entry.getValue() == null){
                iterator.remove();
            }
        }
    }

    public void importData(String data,String format,Map param,Integer serverId){
        Map importParam = new HashMap();
        importParam.put(FORMAT,format);
        importParam.put(RULE,param);
        data = data.replace("\\\"","\"");
        importParam.put(SOURCE,data);
        MWZabbixAPIResult result = zabbixDubboService.getZabbixApiResult(ZabbixApiConstants.GET_CUSTOM_INFO_BY_METHOD, serverId, ZabbixMethodConstants.CONFIGURATION_IMPORT, importParam);
        if(result == null || result.isFail()){
            throw new ZabbixResultException(String.valueOf(result.getData()));
        }
    }
}
